package com.ruiyian.netty.scheduledtask;

// netty定时任务，用于动态更新设备数据

import com.ruiyian.common.constant.Constants;
import com.ruiyian.common.utils.jfinsUtil.FinsMessage;
import com.ruiyian.common.utils.jfinsUtil.FinsMessageUtils;
import com.ruiyian.netty.nettyclient.NettyStarter;
import com.ruiyian.system.domain.ServerEq;
import com.ruiyian.system.service.ServerService;
import io.netty.channel.ChannelFuture;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
@EnableScheduling //开启定时任务
public class NettyScheduleTask {
    private int slectnum = 0;
    private List<ServerEq> serverList;
    @Autowired
    private ServerService serverService;

    @Scheduled(cron = "0/10 * * * * ?") //定时任务注解+cron表达式
    public void testScheduleTask() {
        System.out.println("执行定时任务" + LocalDateTime.now());
        if(slectnum==0)
        {
            serverList = serverService.selectServerByTunnelId((long) 0, 0); // 全部设置为0，获取所有服务列表，只开机获取一次
            slectnum++;
        }
        Map<String, ChannelFuture> connectMap = NettyStarter.getConnectMap(); // 通过netty获取所有连接状态
        if(connectMap.size()==0){
            log.info("无设备连接");
        }
        else{
            // 筛选出在线的plc
            for(int i = 0; i < serverList.size(); i++) {
                if(!connectMap.containsKey(serverList.get(i).getHost() + ":" +serverList.get(i).getPort())){
                    serverList.remove(i);
                    i--;
                }
            }
            // 下发读取信息作为心跳保持
            for(ServerEq oneServerEq:serverList){
                // plc设备下发读数据的指令
                if(oneServerEq.getCode().equals("plc")){
                    FinsMessage finsreadMessage = new FinsMessage();
                    // 如果是二次事故模块
                    if(oneServerEq.getModuleid()==18){
                        // 数据生成
                        finsreadMessage = FinsMessageUtils.createReadFineMessage(130, 75, 1, oneServerEq.getHost() + ":" +oneServerEq.getPort(), Constants.DEFAULT_SA1);
                    }
                    // 视觉诱导模块
                    else if(oneServerEq.getModuleid()==162){
                        finsreadMessage = FinsMessageUtils.createReadFineMessage(130, 210, 1, oneServerEq.getHost() + ":" +oneServerEq.getPort(), Constants.DEFAULT_SA1);
                    }
                    ChannelFuture channelFuture = connectMap.get(oneServerEq.getHost()+":"+oneServerEq.getPort());
                    channelFuture.channel().writeAndFlush(finsreadMessage.toString());
                }
                // 如果其他设备要下发心跳
            }
        }
    }
}
